package admin

import (
	"fmt"
	"gitee.com/jikey/elk-blog/app/model"
	"gitee.com/jikey/elk-blog/app/service"
	"gitee.com/jikey/elk-blog/pkg/e"
	"gitee.com/jikey/elk-blog/pkg/response"
	"gitee.com/jikey/elk-blog/setting"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
	"strconv"
	"strings"
)

type User struct {
	Base
}

// Index 用户资料首页
func (u *User) Index(c *gin.Context) {
	response.HTML(c, "user/index", nil)
}

// Users 用户列表
func (u *User) Users(c *gin.Context) {
	response.HTML(c, "users/index", nil)
}

// Password 密码管理
func (u *User) Password(c *gin.Context) {
	response.HTML(c, "user/password", nil)
}

// Info 用户资料首页
func (u *User) Info(c *gin.Context) {
	data := make(map[string]interface{})

	id, _ := strconv.Atoi(c.Query("id"))
	data["rows"], _ = service.User.Get(id)

	response.Success(c, data)
}

// List 用户列表
func (u *User) List(c *gin.Context) {
	var conditions []string
	data := make(map[string]interface{})
	maps := ""

	pageNum, _ := strconv.Atoi(c.Query("page"))
	username := c.Query("username")

	if len(username) > 0 {
		conditions = append(conditions, fmt.Sprintf("username like '%%%s%%'", username))
	}

	maps = strings.Join(conditions, " AND ")

	rows, total := service.User.List(pageNum, setting.PageSize, maps)

	data["rows"] = rows
	data["total"] = total

	response.Success(c, data)
}

// Insert 新增保存
func (u *User) Insert(c *gin.Context) {
	user := &model.User{}

	if err := c.ShouldBind(&user); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	err := service.User.Create(user)

	if err != nil {
		logrus.Error("新增失败", err)
		response.Fail(c, e.ErrorInsert)
		return
	}

	response.Success(c, user)
}

// Update 修改
func (u *User) Update(c *gin.Context) {
	user := &model.User{}

	if err := c.ShouldBind(&user); err != nil {
		c.JSON(400, gin.H{
			"err": err.Error(),
		})
		return
	}

	id := strconv.Itoa(user.Id)
	err := service.User.Update(id, user)

	if err != nil {
		logrus.Error("修改失败", err)
		response.Fail(c, e.ErrorUpdate)
		return
	}

	user.Password = ""

	response.Success(c, user)
}

// Destory 删除
func (u *User) Destory(c *gin.Context) {
	id := c.PostForm("id")
	service.User.Delete(id)

	response.Success(c, id)
}
